package org.pizza.nacos.loadBalancer;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cloud.loadbalancer.cache.LoadBalancerCacheManager;
import org.springframework.cloud.loadbalancer.core.CachingServiceInstanceListSupplier;
import org.springframework.context.ApplicationListener;

import java.util.List;


/**
 * @author 高巍
 * @since 2020/12/14 1:19 下午
 */
public class ServerListUpdateListener implements ApplicationListener<ServiceInstancesChangedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ServerListUpdateListener.class);

    private LoadBalancerCacheManager loadBalancerCacheManager;

    public ServerListUpdateListener(LoadBalancerCacheManager loadBalancerCacheManager) {
        this.loadBalancerCacheManager = loadBalancerCacheManager;
    }




    @Override
    public void onApplicationEvent(ServiceInstancesChangedEvent serviceInstancesChangedEvent) {
        NamingEvent namingEvent = serviceInstancesChangedEvent.getNamingEvent();

        String serviceName = namingEvent.getServiceName();
        String[] split = serviceName.split(Constants.SERVICE_INFO_SPLITER);
        String serviceId = split[1];
        if (logger.isDebugEnabled()) {
            logger.debug("收到 {} 服务实例变更事件", serviceId);
        }
        Cache cache = loadBalancerCacheManager.getCache(CachingServiceInstanceListSupplier.SERVICE_INSTANCE_CACHE_NAME);
        if(cache!=null){
            List<Instance> instances = namingEvent.getInstances();
            cache.put(serviceId,  NacosServiceDiscovery.hostToServiceInstanceList(instances,serviceId));
        }

    }
}
